using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;

namespace Gameplay.PVE.Editor
{
    public class PveRenameEditor
    {
        [MenuItem("GTATools/GamePlay/PVE/PveRename", false, 66778899)]
        public static void PveRename()
        {
            string[] GUIDs = Selection.assetGUIDs;
            var stringBuilder = new StringBuilder();
            foreach (var guid in GUIDs)
            {
                string path = Application.dataPath.Replace("Assets","") + AssetDatabase.GUIDToAssetPath(guid);

                if (Directory.Exists(path)){  
                    DirectoryInfo direction = new DirectoryInfo(path);  
                    FileInfo[] files = direction.GetFiles("*",SearchOption.AllDirectories);

                    for(int i=0;i<files.Length;i++){  
                        if (files[i].Name.EndsWith(".meta")){  
                            continue;  
                        }
                        string assetName = files[i].Name;
                        string oldName = files[i].DirectoryName + "\\" + files[i].Name;
                        var root = Application.dataPath.Replace("Assets", "");
                        root = root.Replace("/", "\\");
                        var oldPath = oldName.Replace(root, "");
                        string pathName = oldPath;
                        string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetName);
                        string extension = Path.GetExtension(assetName);
                        var extensionLowerCase = extension.ToLowerInvariant();
                        if (extensionLowerCase.Contains(".anim"))
                        {
                            ProcessAnim(assetName, pathName);
                        }
                        else if (extensionLowerCase.Contains(".png") || files[i].Name.Contains(".tga"))
                        {
                            ProcessTexture(assetName, pathName);
                        }
                        else if (extensionLowerCase.Contains(".fbx"))
                        {
                            ProcessMesh(assetName, pathName);
                        }
                        else if (extensionLowerCase.Contains(".mat"))
                        {
                            ProcessMaterial(assetName, pathName);
                        }
                        /*else if (files[i].Name.Contains(".prefab"))
                        {
                            ProcessPrefab(assetName, pathName);
                        }*/
                    }  
                }  
                
            }
            //File.WriteAllText(filePath, stringBuilder.ToString());
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
        [MenuItem("GTATools/GamePlay/PVE/SceneRename", false, 66778899)]
        public static void SceneRename()
        {
            string[] GUIDs = Selection.assetGUIDs;
            foreach (var guid in GUIDs)
            {
                string path = Application.dataPath.Replace("Assets","") + AssetDatabase.GUIDToAssetPath(guid);

                if (Directory.Exists(path)){  
                    DirectoryInfo direction = new DirectoryInfo(path);  
                    FileInfo[] files = direction.GetFiles("*",SearchOption.AllDirectories);

                    for(int i=0;i<files.Length;i++){  
                        if (files[i].Name.EndsWith(".meta")){  
                            continue;  
                        }
                        string assetName = files[i].Name;
                        string oldName = files[i].DirectoryName + "\\" + files[i].Name;
                        var root = Application.dataPath.Replace("Assets", "");
                        root = root.Replace("/", "\\");
                        var oldPath = oldName.Replace(root, "");
                        string pathName = oldPath;
                        string extension = Path.GetExtension(assetName);
                        var extensionLowerCase = extension.ToLowerInvariant();
                        if (extensionLowerCase.Contains(".png") || extensionLowerCase.Contains(".tga"))
                        {
                            var names = files[i].DirectoryName.Split('\\');
                            ProcessTextureScene(assetName, pathName,names[names.Length-1]);
                        }
                    }  
                }  
                
            }
            //File.WriteAllText(filePath, stringBuilder.ToString());
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }

        private static void ProcessPrefab(string assetName, string pathName)
        {
            
        }

        private static void ProcessMaterial(string assetName, string pathName)
        {
            // 处理非法字符
            assetName = assetName.Replace(" ", "")
                .Replace("-", "_")
                .Replace("(1)", "_1")
                .Replace("#", "")
                .Replace("[0]", "_0")
                .Replace("[1]", "_1")
                .Replace("(","_")
                .Replace(")","");

            // 处理其他表示material的前缀
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetName);
            var nameParts = fileNameWithoutExtension.Split(new[] {'_'}, StringSplitOptions.RemoveEmptyEntries);
            string finalName = "mat";

            foreach (var namePart in nameParts)
            {
                if (namePart == "Material" ||
                    namePart == "material" ||
                    namePart == "mat" ||
                    namePart == "Mat" ||
                    namePart == "m" ||
                    namePart == "M")
                {
                    continue;
                }

                finalName += "_" + namePart.Replace("Material", "").Replace("Mat", "");
            }
            AssetDatabase.RenameAsset(pathName, finalName);
        }

        private static void ProcessMesh(string assetName, string pathName)
        {
            // 处理非法字符
            assetName = assetName.Replace(" ", "_").Replace("-", "_")
                .Replace("(1)", "_1")
                .Replace("(","_")
                .Replace(")","");
            string finalName = "mesh";
            if (assetName.Contains("@a_"))
            {
                finalName = assetName;
                ModelImporter importer = (ModelImporter)AssetImporter.GetAtPath(pathName);
                if (importer.animationType == ModelImporterAnimationType.Human && !assetName.Contains("_hum"))
                {
                    finalName = finalName.Replace("@a_", "@a_hum_");
                }
            }
            else
            {
                // 处理文件名
                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetName);
                var nameParts = fileNameWithoutExtension.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);

                ModelImporter importer = (ModelImporter)AssetImporter.GetAtPath(pathName);
                if (importer.animationType == ModelImporterAnimationType.Human && !assetName.Contains("_hum"))
                {
                    finalName += "_hum";
                }
                foreach (var namePart in nameParts)
                {
                    if (namePart == "fbx" ||
                        namePart == "mesh" ||
                        namePart == "mod" ||
                        namePart == "Model" ||
                        namePart == "m")
                    {
                        continue;
                    }

                    finalName += "_" + namePart.Replace("Model", "");
                }
            }
            AssetDatabase.RenameAsset(pathName, finalName);
        }

        private static void ProcessTextureScene(string assetName, string pathName,string sceneName)
        {
            // 处理非法字符
            assetName = assetName.Replace(" ", "_").Replace("-", "_").Replace("(1)", "_1");

            // 处理其他表示texture的前缀
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetName);
    
            var nameParts = fileNameWithoutExtension.Split(new [] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            string finalName = "tex";

            if (!assetName.Contains(sceneName))
            {
                finalName += "_";
                finalName += sceneName;
            }
            

            foreach (var namePart in nameParts)
            {
                if (namePart == "texture" ||
                    namePart == "t" ||
                    namePart == "T" ||
                    namePart == "tes" ||
                    namePart == "tex" ||
                    namePart == "tx")
                {
                    continue;
                }
                
                finalName += "_" + namePart.Replace("Texture", "").Replace("Tex", "");
            }
            if (!finalName.Contains("2048") && !finalName.EndsWith("_n"))
            {
                finalName += "_2048";
            }
            
            AssetDatabase.RenameAsset(pathName, finalName);
        }
        
        private static void ProcessTexture(string assetName, string pathName)
        {
            // 处理非法字符
            assetName = assetName.Replace(" ", "_").Replace("-", "_").Replace("(1)", "_1");

            // 处理其他表示texture的前缀
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetName);
    
            var nameParts = fileNameWithoutExtension.Split(new [] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            string finalName = "tex";

            foreach (var namePart in nameParts)
            {
                if (namePart == "texture" ||
                    namePart == "t" ||
                    namePart == "T" ||
                    namePart == "tes" ||
                    namePart == "tex" ||
                    namePart == "tx")
                {
                    continue;
                }

                finalName += "_" + namePart.Replace("Texture", "").Replace("Tex", "");
            }
            AssetDatabase.RenameAsset(pathName, finalName);
        }
        
        private static string groupRegex = @"(.*?)\\";
        
        private static void ProcessAnim(string assetName,string pathName,int matchIndex = 5)
        {
            // 处理非法字符
            assetName = assetName.Replace(" ", "_")
                .Replace("-", "_")
                .Replace("(1)", "_1")
                .Replace("#", "")
                .Replace("[0]", "_0")
                .Replace("[1]", "_1")
                .Replace("(","_")
                .Replace(")","");

            // 处理其他表示animation的前缀
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(assetName);
            var nameParts = fileNameWithoutExtension.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
            string finalName = "ani";

            //string matchRootName = string.Empty;
            //var allMatches = Regex.Matches(pathName, groupRegex);
            foreach (var namePart in nameParts)
            {
                if (namePart == "a" ||
                    namePart == "A" ||
                    namePart == "anim" ||
                    namePart == "ani")
                {
                    continue;
                }

                finalName += "_" + namePart.Replace("Anim", "").Replace("Animation", "");
            }
                        
            AssetDatabase.RenameAsset(pathName, finalName);
        }
    }
}